﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace MSP.Data.Domain.Enums
{
    public static class EnumExtensions
    {
        public static string GetDescription(this Enum enumValue)
        {
            FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false);

            if (attributes != null && attributes.Length > 0)
                return attributes[0].Description;
            else
                return enumValue.ToString();
        }

        public static string GetDescription<T>(int value)
        {
            var enumValue = (Enum)Enum.ToObject(typeof(T), value);
            return GetDescription(enumValue);
        }

        public static string GetDescription<T>(string value)
        {
            string retVal = string.Empty;
            if (!string.IsNullOrEmpty(value))
            {
                var enumValue = (Enum)Enum.Parse(typeof(T), value);
                retVal = GetDescription(enumValue);
            }

            return retVal;
        }
    }
}
